package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.impl.EmployeeServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServiceImpl employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee ,HttpSession session){
        //判断employee是否存在空值
        /*if(employee.getUsername() == null || employee.getPassword() == null){
            return R.error("用户名和密码不能为空");
        }*/
        if(StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())){
            return R.error("用户名和密码不能为空");
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee sourceEmp = employeeService.getOne(lqw);

        //校验用户名是否存在(sourceEmp是否为空)
        if(sourceEmp == null){
            return R.error("账户不存在");
        }

        //校验账户是否禁用
        if(sourceEmp.getStatus() == 0){
            return R.error("账户已禁用");
        }
        //校验密码
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if(password.equals(sourceEmp.getPassword())){
            sourceEmp.setPassword(null);
            session.setAttribute("loginUser",sourceEmp);
            return R.success(sourceEmp);
        }else {
            return R.error("用户名或密码错误");
        }


    }

    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.success(null);
    }

    @PostMapping
    public R addEmployee(@RequestBody Employee employee,HttpSession session){
        //检查并处理数据
        //添加默认密码123456,并加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //添加处理时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //添加处理人(当前登陆人)id
//        Employee loginUser = (Employee) session.getAttribute("loginUser");
//        employee.setCreateUser(loginUser.getId());
//        employee.setUpdateUser(loginUser.getId());

        boolean save = employeeService.save(employee);
        if(save){
            return R.success(null);
        }
        return R.error("null");
    }

    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){
        IPage<Employee> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(name)){
            lqw.like(Employee::getName,name);
        }
        employeeService.page(pageinfo,lqw);
        List<Employee> records = pageinfo.getRecords();
        long total = pageinfo.getTotal();
        Map<Object, Object> data = new HashMap<>();
        data.put("records",records);
        data.put("total",total);
        return R.success(data);

    }

    @PutMapping
    public R updataById(@RequestBody Employee employee,HttpSession session){
        //设置修改时间和修改人(当前登录者)
//        employee.setUpdateTime(LocalDateTime.now());
//        Employee loginUser = (Employee) session.getAttribute("loginUser");
//        employee.setUpdateUser(loginUser.getId());
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("用户不存在");
    }

    @GetMapping("/export")
    public R exportEmployee(HttpServletResponse response){

        try {
            List<Employee> list = employeeService.list();

            response.setHeader("Content-Disposition","attachment;filename=employrr.xlsx");
            EasyExcel.write(response.getOutputStream(),Employee.class).sheet("员工数据").doWrite(list);

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }
}
